package com.xunce.xcworkservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunce.xcworkservice.entity.AccountRoles;
import com.xunce.xcworkservice.dao.AccountRolesMapper;
import com.xunce.xcworkservice.service.AccountRolesService;

import java.util.List;

/**
 * @ClassName:  AccountRolesServiceImpl  
 * @Author:     yanlong.guo      
 * @Date:       2023/12/15 17:47   
 */

@Service
public class AccountRolesServiceImpl extends ServiceImpl<AccountRolesMapper, AccountRoles> implements AccountRolesService{

    // 更新用户角色信息
    @Override
    public Boolean updateAccountRole(Integer accountId, List<Integer> roleIds){
        QueryWrapper<AccountRoles> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AccountRoles::getAccountId, accountId);
        List<AccountRoles> accountRolesList = list(wrapper);
        List<Integer> oldRoleIds = accountRolesList.stream().map(AccountRoles::getRoleId).toList();
        if (roleIds.equals(oldRoleIds)){
            return true;
        }
        //删除旧的
        if (oldRoleIds.size() > 0){
            LambdaQueryWrapper<AccountRoles> delWrapper = new LambdaQueryWrapper<>();
            delWrapper.eq(AccountRoles::getAccountId, accountId);
            remove(delWrapper);
        }
        //添加新的
        for (Integer roleId : roleIds){
            AccountRoles accountRoles = new AccountRoles();
            accountRoles.setAccountId(accountId);
            accountRoles.setRoleId(roleId);
            save(accountRoles);
        }
        return true;
    }
}
